<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Session, DB, Hash, Validator,Config;

class LoginController extends Controller
{
    // 登录页面
    public function login(Request $request)
    {
        $data = $request->old();
        return view("home.login", compact("data"));
    }

    //验证码
    public function captcha()
    {
        // 生成验证码图片的Builder对象 配置相应的属性
        $builder = new CaptchaBuilder;
        // 可以设置图片的宽高及字体
        $builder->build(76, 40, null);
        // 获取验证码的内容
        $phrase = $builder->getPhrase();


        // 把内容存入session
        Session::flash('code', $phrase);
        // 生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

    //登陆验证
    public function logTodo(Request $request)
    {
//        dd($request);   //DeBug
        //接受数据
        $data = $request->all();
        //验证码是否正确
        if (session("code") != $data["code"]) {
            $request->flash();
            return back()->with(["info" => "验证码错误"]);
        }

        //有效性验证
        $this->validate($request, [
            "uname" => "required",
            "password" => "required|between:6,15",
        ], [
            "uname.required" => "账号未填写",
            "password.required" => "密码不能为空",
            "password.between" => "密码长度应为6-15位"
        ]);
//        dd($data);
        //真实性验证
        $userRec = DB::table("user")->where("user_name", $data["uname"])->first();
//		dd($userRec);exit;
        if (empty($userRec)) {
            $request->flash();
            return back()->with(["info" => "账号不存在"]);
//
        } else if (!Hash::check($data["password"], $userRec->user_pass)) {
            $request->flash();
            return back()->with(["info" => "密码错误"]);
        } else {//返回结果
            // 修改登录时间
            $ip = $request->ip();
            $time = date('Y-m-d H:i:s');
            DB::table('user')->where('id', $userRec->id)->update(['user_logintime'=>$time, 'user_loginip'=>$ip]);
            // 重新获取
            $userRec = DB::table('user')->where('id', $userRec->id)->first();
            //将用户状态写入session
            session(["userData" => $userRec]);
            // 回首页
            $callback = url('/');
            return redirect($callback);
        }
    }

    // 注册验证
    public function store(Request $request)
    {
        //执行数据验证
        $this->validate($request, [
            "user_name" => "required|unique:user",
            "user_pass" => "required|between:6,15",
            "repassword" => "required|same:user_pass",
            "code" => "required",

        ], [
            "user_name.required" => "账号不能为空",
            "user_name.unique" => "账号已被占用",
            "user_pass.required" => "密码不能为空",
            "user_pass.between" => "密码长度应为6-15位",
            "repassword.required" => "确认密码必须填写",
            "repassword.same" => "两次密码输入不一致",
            "code.required" => "验证码必须填写"
        ]);
        $code = $request->get('code');
        if (session("code") != $code) {
            return back()->with(["info" => "验证码错误"]);
        }
        //提取出数据并重组
        $data = $request->except("_token", "repassword", "code");
        $data["user_pass"] = Hash::make($data["user_pass"]);
//        dd($data);
        //执行数据创建
        if (FALSE !== $insertID = DB::table("user")->insertGetId($data)) {
            $message = new \App\Model\Message();
            $data = [
                'msg_title'=>'注册成功的系统消息',
                'msg_content'=>'尊敬的'.$data['user_name'].'，您已经注册成为'.Config::get('web.web_domain').'的会员，请您在发表言论时，遵守当地法律法规。如果您有什么疑问可以联系管理员，Email: '.Config::get('web.web_email').'。',
            ];
            $message->autoSendMessage($insertID,$data);
            return redirect("/login");
//            return "1111";
        } else {
            return back()->with(["info" => "添加用户失败"]);
        }
    }

    //退出登陆
    public function logout()
    {
        //销毁session
        Session::forget("userData");
        return redirect("/");
    }
}
